package com.caj;

import com.caj.id.Redis;
import com.caj.id.SnowFlake;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;

@SpringBootTest(classes = DistributeId.class)
@RunWith(SpringRunner.class)
public class test {

    @Test
    public void test(){
        CountDownLatch count = new CountDownLatch(1000);
        SnowFlake snowFlake = new SnowFlake(10,20);
        for (int i = 0; i < 1000; i++) {
            //模拟1000个线程并发
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        count.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    getSnowFlake(snowFlake);
                }
            }).start();
            count.countDown();
        }
    }

    @Test
    public void test1() throws InterruptedException {
        CountDownLatch count = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            //模拟1000个线程并发
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        count.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    Redis redis = new Redis();
                    System.out.println("insert into order(order_id) values('" + redis.nextId() + "')");
                }
            }).start();
            count.countDown();
        }
        Thread.sleep(1000000);
    }

    private void getSnowFlake(SnowFlake snowFlake){
        long value = snowFlake.nextId();
        System.out.println("insert into order(order_id) values('"+value+"')");
    }

}
